using AngleSharp.Extensions;
using AngleSharp.Parser.Html;
using System.Collections.Generic;
using System.Linq;

namespace Sustainalytics.ScreeningTool.Synchronization
{
    public static class StringExtensions
    {
        public const string LineBreakReplacement = "  ";

        public static string StripLineBreaks(this string value) => value?
            .Replace("\r\n", LineBreakReplacement)
            .Replace("\r", LineBreakReplacement)
            .Replace("\n", LineBreakReplacement);

        public static string StripHtmlTags(this string value)
        {
            if (string.IsNullOrEmpty(value))
                return value;

            var parser = new HtmlParser();
            var nodeList = parser.ParseFragment(value, null);
            return string.Concat(nodeList.Select(x => x.Text()));
        }

        public static string JoinStrings(this IEnumerable<string> values, string separator = "")
        {
            if (values == null || !values.Any())
                return null;

            return string.Join(separator, values.Where(x => !string.IsNullOrWhiteSpace(x)));
        }

        public static string EnsureEndsWithPeriod(this string value)
        {
            if (string.IsNullOrWhiteSpace(value))
                return "";

            var trimmedValue = value.Trim();

            if (!trimmedValue.EndsWith("."))
                return trimmedValue + ".";

            return trimmedValue;
        }

        public static IEnumerable<string> EnsureEndsWithPeriod(this IEnumerable<string> values)
            => values?.Select(x => x.EnsureEndsWithPeriod());
    }
}
